package com.itcast.rpc.core.server;

import com.itcast.rpc.core.server.initializer.ServiceInitializer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @program: bio_tcp
 * @description:
 * @author: zhanghz001
 * @create: 2021-02-23 10:59
 **/
public class NettyRpcServer {
    private static final Logger LOGGER = LoggerFactory.getLogger(NettyRpcServer.class);
    
    public static void start(String host, int port) {
        doStart(host, port);
    }
    
    private static void doStart(String host, int port) {
        //监控客户端连接的主线程
        NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
        
        //处理已经连接的客户端请求,默认线程池大小cpu*2
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();
        
        try {
            
            //创建server的主线程
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            
            //绑定两个监控线程池
            serverBootstrap.group(bossGroup, workerGroup);
            
            //绑定服务端需要使用的channel类型
            serverBootstrap.channel(NioServerSocketChannel.class);
            
            //进行pipeline的绑定,并在pipeline中加入channelhandler
            serverBootstrap.childHandler(new ServiceInitializer());
            //绑定监听端口
            ChannelFuture future = serverBootstrap.bind(host, port).sync();
            
            LOGGER.info("服务器启动完成，地址为：" + host + ":" + port);
            
            //监听channel的关闭请求
            future.channel().closeFuture().sync();
        } catch (Exception e) {
            LOGGER.error("服务器启动失败！", e);
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
